<?php
class PublicAction extends CommonAction {
    public $weixin;
    public function _initialize() {
		$this->initCommon();
        //parent::_initialize();
        Vendor('Weixin.Weixin');
        $d['token'] = getSysVal('token');
        $d['appid'] = getSysVal('appid');
        $d['appsecret'] = getSysVal('appsecret');
        $this->weixin = new WeixinChat($d);
    }
    //会员注册
    public function reg() {
        $this->display();
    }
    //会员登录
    public function login() {
        if ($this->memberInfo) {
            redirect(U('Member/Index/index'));
        } else {
            if ($this->is_weixin() && $this->siteInfo['is_wxLogin'] > 0) {
				if($this->siteInfo['is_wxLogin'] == 1){
					$snsapi_base = 1;
				}elseif($this->siteInfo['is_wxLogin'] == 2){
					$snsapi_base = 0;
				}
				$domain = explode(',', $this->siteInfo['domain']);
				if($domain[0] == ''){
					$siteurl = $_SERVER['SERVER_NAME'];
				}else{
					$siteurl = $domain[0];
				}
                $this->weixin->redirectGetOauthCode('http://' . $siteurl . __APP__ . "/Member/Public/getcode.html", $snsapi_base, intval($_COOKIE['aff_id']).'_and_'.base64_encode(session('jumpurl')));
            }
            if ($this->_get('type')) {
                $str = $this->createloginid();
                //echo $str;
                setcookie('spwd', md5($str) , time() + 1800, '/');
                $tiket = $this->weixin->createQrcode($str);
                $this->assign('tiket', $tiket);
            } else {
                redirect(U('Member/Public/login', array(
                    'type' => '1'
                )));
            }
        }
        $this->display();
    }
    private function createloginid() {
        $str = rand(100000, 999999);
        $ret = M('Member')->where(array(
            'site_id' => __SITEID__,
            'loginid' => md5($str)
        ))->find();
        if (is_array($ret)) {
            $this->createloginid();
        }
        return $str;
    }
    //会员登出
    public function logout() {
        session('memberInfo',NULL);
        $this->success('退出成功');
    }
    //会员登录验证
    public function doLogin() {
        if ($this->_post('password') && $this->_post('username')) {
            $map['password'] = md5($this->_post('password'));
            $map['_logic'] = 'and';
            $map['site_id'] = __SITEID__;
            $map['username'] = $this->_post('username');
            $memberModel = D('Member');
            if ($memberModel->checkLogin($map)) {
                session('memberInfo', $memberModel->userInfo);
                //跳转到认证前页面
                if (session('jumpurl')) {
                    //$this->assign('jumpUrl',session('jumpurl'));
                    $url = session('jumpurl');
                    session('jumpurl',NULL);
                } else {
                    //$this->assign('jumpUrl',U('Index/index'));
                    if ($this->memberInfo['site_id'] == 29) {
                        $url = U('Member/Vcard/edit');
                    } else {
                        $url = U('Index/index');
                    }
                } 
                $this->success('登录成功', $url);
            } else {
                $this->error($memberModel->loginError);
            }
        } else {
            $this->error('请输入用户和密码');
        }
    }
    //微信扫描登录
    public function weixinDoLogin() {
        if ($this->_post('pass')) {
            if ($_COOKIE['spwd'] == '') {
                $this->error('登录参数出错');
                exit();
            }
            $db = M('Member');
            $ret = $db->where(array(
                'site_id' => __SITEID__,
                'loginid' => $_COOKIE['spwd']
            ))->find();
            if (is_array($ret)) {
                //$this->success('登录成功');
                setcookie('spwd', NULL);
                $db->where(array(
                    'site_id' => __SITEID__,
                    'openid' => $ret['openid']
                ))->data(array(
                    'loginid' => ''
                ))->save();
                $map['_logic'] = 'and';
                $map['site_id'] = __SITEID__;
                $map['openid'] = $ret['openid'];
                $memberModel = D('Member');
                if ($memberModel->checkLogin($map)) {
                    session('memberInfo', $memberModel->userInfo);
                    //跳转到认证前页面
                    if (session('jumpurl')) {
                        //$this->assign('jumpUrl',session('jumpurl'));
                        $url = session('jumpurl');
                        session('jumpurl',NULL);
                    } else {
                       
                            $url = U('Index/index');

                    }
                    $this->success('登录成功', $url);
                } else {
                    $this->error($memberModel->loginError);
                }
            } else {
            }
        }
    }
    //异步登录
    public function ajaxdoLogin() {
        if ($this->_post('password') && $this->_post('username')) {
            $map['password'] = md5($this->_post('password'));
            $map['_logic'] = 'and';
            $map['site_id'] = __SITEID__;
            $map['username'] = $this->_post('username');
            $memberModel = D('Member');
            if ($memberModel->checkLogin($map)) {
                session('memberInfo', $memberModel->userInfo);
                //跳转到认证前页面
                $this->assign('info', $memberModel->userInfo);
                $authentication_DB = M('Authentication');
                $authentication = $authentication_DB->where(array(
                    'member_id' => $this->memberInfo['id']
                ))->find();
                //dump($authentication);
                $this->assign('authentication', $authentication);
                $redata['info'] = '登录成功';
                $redata['data'] = $this->fetch();
                $redata['status'] = 1;
            } else {
                $redata['info'] = $memberModel->loginError;
                $redata['status'] = 0;
                $redata['data'] = '';
            }
        } else {
            $redata['info'] = '请填写用户名和密码';
            $redata['status'] = 0;
            $redata['data'] = '';
        }
        echo json_encode($redata);
        exit();
    }
    //检查验证码
    function check_verify($code, $id = '') {
        import('@.ORG.Verify');
        $verify = new Verify();
        return $verify->check($code, $id);
    }
    //会员注册
    public function doReg() {
        if ($this->_post('username')) {
            $_POST['site_id'] = __SITEID__;
            $memberModel = D('Member');
            if (isset($_COOKIE['aff_id']) && intval($_COOKIE['aff_id']) > 0) {
                $_POST['pid'] = intval($_COOKIE['aff_id']);
            }
            $_POST['password'] = md5($_POST['password']);
            $_POST['repassword'] = md5($_POST['repassword']);
            if (!$memberModel->create()) {
                $this->error($memberModel->getError());
            }
            $user = $memberModel->where(array(
                'site_id' => __SITEID__,
                'username' => $this->_post('username')
            ))->find();
            if (is_array($user)) {
                $this->error('该用户已经被注册');
            }
            $id = $memberModel->add();
            if (false === $id) {
                $this->error($memberModel->getError());
            } else {
                $data = $memberModel->where(array(
                    'id' => $id
                ))->find();
                session('memberInfo', $data);
                
                    $this->success('注册成功', U('Member/Index/index'));

            }
        } else {
            $this->error('请填写信息');
        }
    }
    
    public function getcode() {
        $memberModel = D('Member');
		//exit($_GET['code']);
        $access_token = $this->weixin->getSnsAccessToken($_GET['code']);
		if(isset($_GET['state'])){
		    $statepid = explode('_and_', $_GET['state']);
		}else{
			$statepid = array(0,'');
		}//echo ($_GET['state']);exit;
		//dump($access_token);exit;
		if($this->siteInfo['is_wxLogin'] == 1){
			
            $login_result = $this->weixin->getSnsUserInfo($access_token['access_token'], $access_token['openid']);
		}else{
			
		    $login_result = $this->weixin->getUserInfo($access_token['openid']);
		}
		
        $where['openid'] = $login_result['openid'];
        $member = $memberModel->where($where)->find();
        if ($member) {
            if ($member['nickname'] == '') {
                $login_result['id'] = $member['id'];
                if ($memberModel->savewx($login_result)) {
					
					
					if($statepid[1] != ''){
						redirect(base64_decode($statepid[1]));
                        exit();
					}
					
                    redirect(U('Member/Index/index'));
                    exit();
                };
            }
            session('memberInfo', $member);
            if($statepid[1] != ''){
				redirect(base64_decode($statepid[1]));
				exit();
			}else {
                redirect(U('Member/Index/index'));
            }
        } else {
            if ($login_result) {
				
                //会员表信息
                $user['site_id'] = __SITEID__;
                $user['openid'] = $login_result['openid'];
                $user['nickname'] = parseWeixinName($login_result['nickname']);
                $user['sex'] = intval($login_result['sex']);
				$user['img_url'] = $login_result['headimgurl'];
				$user['reg_time']=time();
				
                //插入会员
                $id = $memberModel->add($user);
                $memberModel->addUser($id);
				$data = array('username' => 'weixin'.$id);
				$data['pid'] = intval($statepid[0]);
				
				
				//清除推荐ID
				setcookie('aff_id', '', time()-1, '/');
				$sret = $memberModel -> updatePid($id, $data['pid']);
				
				//exit($memberModel -> getLastSql());
				//推送信息
				$userlist = $memberModel -> getUserArr($data['pid']);
				//发送通知
				
				foreach($userlist as $k => $v){
					sendWXMsg($v['openid'], 'V'.($v['deep']).'客户加入');
				}
				
                $data = $memberModel->where(array(
                    'id' => $id
                ))->find();
                session('memberInfo', $data);
               
                if ($id > 0) {
				if($statepid[1] != ''){
						redirect(base64_decode($statepid[1]));
                        exit();
					}
                    redirect(U('Member/Index/index'));
                } else {
                    $this->error('登陆错误');
                }
            }
        }
		exit('登录错误！获取信息错误，可能是接口密钥设置有误。');
        //$this->display();
    }
    public function getWeixinAddress() {
        Vendor('Weixin.Weixin');
        $d['token'] = getSysVal('token');
        $d['appid'] = getSysVal('appid');
        $d['appsecret'] = getSysVal('appsecret');
        $this->weixin = new WeixinChat($d);
        $this->assign('addressSign_info', $this->weixin->getSignPackage());
        //dump($this->weixin->getSignPackage());
        $this->display();
    }
}
